package com.learning.bio.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: wcl
 * @Description:
 * @Date: Create in 3:33 PM 2018/11/1
 * @Modified By:
 */

public class BaseUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(BaseUtils.class);

    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    /**
     * 核心线程数量大小
     */
    private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
    /**
     * 线程池最大容纳线程数
     */
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;

    private static ExecutorService threadPool;

    public synchronized static ExecutorService getThreadPool() {

        if (threadPool != null) {
            return threadPool;
        }
        AtomicInteger mCount = new AtomicInteger(1);
        threadPool = new ThreadPoolExecutor(CORE_POOL_SIZE,
                MAXIMUM_POOL_SIZE, 60L, TimeUnit.SECONDS,
                new SynchronousQueue<>(), runnable -> new Thread(runnable, "msThread #" + mCount.getAndIncrement()));

        return threadPool;
    }

    public static void close(Closeable closeable, String ioName) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                LOGGER.info("{}关闭失败:{}", ioName, closeable);
            }
        }
    }

}
